'use strict';

function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
}
function generateCalendar(year, month) {
    const daysInWeek = 7;
    const dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; // 周几映射
    // 获取当前月份的第一天和最后一天
    const firstDayOfMonth = new Date(year, month - 1, 1);
    const lastDayOfMonth = new Date(year, month, 0);
    // 当前月份总天数
    const daysInMonth = lastDayOfMonth.getDate();
    // 获取第一天是星期几，0 = 周日, ..., 6 = 周六
    const firstDayOfWeek = firstDayOfMonth.getDay();
    // 前一个月的最后一天
    const prevMonthLastDay = new Date(year, month - 1, 0).getDate();
    // 计算需要补全的前后日期天数
    const prevDaysToFill = firstDayOfWeek; // 前补天数
    const nextDaysToFill = daysInWeek - ((prevDaysToFill + daysInMonth) % daysInWeek || daysInWeek); // 后补天数
    const calendar = [];
    // 添加前一个月的日期
    for (let i = prevDaysToFill; i > 0; i--) {
        const day = prevMonthLastDay - i + 1;
        const date = new Date(year, month - 2, day);
        calendar.push({
            date,
            meta: {
                year: date.getFullYear(),
                month: date.getMonth() + 1,
                day: date.getDate(),
                dayOfWeek: dayNames[date.getDay()],
                formattedDate: formatDate(date),
                type: "prev",
            },
        });
    }
    // 添加当前月的日期
    for (let i = 1; i <= daysInMonth; i++) {
        const date = new Date(year, month - 1, i);
        calendar.push({
            date,
            meta: {
                year: date.getFullYear(),
                month: date.getMonth() + 1,
                day: date.getDate(),
                dayOfWeek: dayNames[date.getDay()],
                formattedDate: formatDate(date),
                type: "current",
            },
        });
    }
    // 添加下一个月的日期
    for (let i = 1; i <= nextDaysToFill; i++) {
        const date = new Date(year, month, i);
        calendar.push({
            date,
            meta: {
                year: date.getFullYear(),
                month: date.getMonth() + 1,
                day: date.getDate(),
                dayOfWeek: dayNames[date.getDay()],
                formattedDate: formatDate(date),
                type: "next",
            },
        });
    }
    return calendar;
}

exports.generateCalendar = generateCalendar;
